from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base, DeclarativeMeta
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import database_exists, create_database

from config import SQLALCHEMY_DATABASE_URI
import json


engine = create_engine(
    SQLALCHEMY_DATABASE_URI,
    json_serializer=lambda obj: json.dumps(obj, ensure_ascii=False), # 序列化
    pool_pre_ping=True, # 连接池预检查
    pool_recycle=3600 # 连接池回收(单位:秒)
)

# 如果数据库不存在，则创建数据库
if not database_exists(engine.url):
    create_database(engine.url)


# 创建会话
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)

# 创建基类
Base: DeclarativeMeta = declarative_base()
